import { Image, Button, message, Tag, InputNumber, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

import commonService from '@/api/services/commonService';
import LeftImg from '@/assets/img/left.png';
import RightImg from '@/assets/img/right.png';
import useUserStore from '@/store/userStore';
import { toEditor } from '@/utils';
import { toYuan } from '@/utils/format-number';

import './detail.css';

export default function GoodsDetailPage() {
  const { id } = useParams();
  const [goods, setGoods] = useState<any>({});
  // const [design, setDesign] = useState<any>({});
  const [params, setParams] = useState<any>({ num: 1, color: '' });
  const [imgs, setImgs] = useState([]);
  const [sizes, setSizes] = useState([]);
  const [colors, setColors] = useState([]);
  const [bigImg, setBigImg] = useState<any>({ url: '', index: 0 });
  const [detail, setDetail] = useState('');
  const [coupons, setCoupons] = useState<any>([]);
  const [info, setInfo] = useState<string>('');

  const [dataSource, setDataSource] = useState<any>([]);
  const [step, setStep] = useState<number>(0);

  useEffect(() => {
    setDataSource(imgs.slice(step, step + 4));
  }, [step, imgs]);

  const handleLeft = () => {
    setStep(step - 4);
  };

  const handleRight = () => {
    setStep(step + 4);
  };

  useEffect(() => {
    commonService.getCustomApi('/front/mall/detail', { fpId: id }).then((res) => {
      setGoods(res.finishedProduct);
      // setDesign(res.preProduct);
      const sizeList = JSON.parse(res.finishedProduct.sizePrice || '[]') || [];
      const tempImgs = JSON.parse(res.finishedProduct.previewThumbs || '[]') || [];
      const cs = JSON.parse(res.finishedProduct.colors || '[]') || [];
      setCoupons(res.couponLibList);
      setImgs(tempImgs);
      setSizes(sizeList);
      setBigImg({ url: tempImgs[0], index: 0 });
      setDetail(res.preProduct.detail);
      setColors(
        cs.filter((item: any) => {
          return item;
        }),
      );
      setParams({
        fpId: res.finishedProduct.id,
        num: 1,
        color: res.finishedProduct.color,
        size: sizeList[0].size,
      });
      console.log(res, 333, cs);
    });
  }, []);

  const toBuy = async () => {
    if (!params.size) {
      message.error('选择尺码');
    }
    await commonService.addCartApi(params);
    setTimeout(() => {
      if (!useUserStore.getState().showLogin) message.success('加入成功');
    }, 1000);
  };

  const receive = (coupon: any) => {
    const { userToken } = useUserStore.getState();
    if (userToken.accessToken) {
      commonService.getCustomApi('/member/coupon/receive', { couponId: coupon.id }).then(() => {
        message.success('领取成功！');
      });
    } else {
      useUserStore.getState().actions.setShowLogin(true);
    }
  };

  const onTabsChange = (key: string) => {
    if (key === 'desc') {
      return false;
    }
    getDetail(key);
  };

  const getDetail = (domainId: any) => {
    commonService.getCustomApi('/common/baseProperty/get', { domainId }).then((res) => {
      setInfo(res?.detail || '');
    });
  };

  const list: any = [
    { title: '尺码表', id: '60' },
    { title: '工艺说明', id: '61' },
    { title: '运费', id: '62' },
    { title: '服务', id: '63' },
  ];

  return (
    <div className="relative left-[50%] ml-[-712px] mt-[50px] flex w-[1424px] flex-col">
      <div className="flex gap-[40px]">
        {/* 左侧图片 */}
        <div className="flex flex-col">
          <div className="relative mb-[24px] h-[600px] w-[700px] overflow-hidden">
            <Image src={bigImg.url} alt="big-img" />
          </div>
          <div className="width-[800px] relative flex min-w-[700px] overflow-hidden">
            <div className="absolute left-[6px] top-[36%] z-[888]">
              <Button onClick={handleLeft} size="large" shape="circle" disabled={step === 0}>
                <img className="h-[40px] w-[40px]" src={LeftImg} alt="left" />
              </Button>
            </div>
            <div className="absolute right-[6px] top-[36%] z-[888]">
              <Button
                onClick={handleRight}
                size="large"
                shape="circle"
                disabled={step + 4 >= imgs.length}
              >
                <img className="h-[40px] w-[40px]" src={RightImg} alt="right" />
              </Button>
            </div>
            <div className="flex gap-[20px] overflow-x-auto overflow-y-hidden">
              {dataSource.map((item: string, index: number) => {
                return (
                  <div
                    onClick={() => {
                      setBigImg({ url: item, index });
                    }}
                    className={[
                      'h-[160px]',
                      'w-[160px]',
                      index === bigImg.index ? 'active' : '',
                    ].join(' ')}
                    key={index}
                  >
                    <Image src={item} preview={false} alt="img" />
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        {/* 右侧属性 */}
        <div className="flex flex-col">
          <div className="flex flex-col gap-[40px] text-[28px] leading-[40px]">
            <div className="font-weight">{goods.goodsName}</div>
            <div>
              <div>￥{toYuan(goods.price)}</div>
              <div className="mt-[12px] text-[20px] text-[#686B73]">每件，含正面印花，不含运费</div>
            </div>
            <div>
              <div className="text-[24px]">颜色：</div>
              <div className="mt-[12px] flex gap-[10px] text-[16px]">
                {colors.map((item: any, index: number) => {
                  return (
                    <div
                      key={index}
                      // onClick={() => {
                      //   setParams({ ...params, color: item.cn });
                      // }}
                      style={{ backgroundColor: item.color }}
                      className={[
                        'color-item h-[20px] w-[20px] cursor-pointer rounded-[50%]',
                        item.cn === params.color ? 'active' : '',
                      ].join(' ')}
                    />
                  );
                })}
              </div>
              <div className="text-[14px]">当前颜色：{params.color}</div>
            </div>
            <div>
              <div className="text-[24px]">尺码：</div>
              <div className="mt-[12px] flex gap-[10px]">
                {sizes.map((item: any) => {
                  return (
                    <Tag
                      onClick={() => {
                        setParams({ ...params, size: item.size, price: item.price });
                      }}
                      key={item.size}
                      className="cursor-pointer"
                      color={item.size === params.size ? 'orange' : 'grey'}
                    >
                      {item.size}
                    </Tag>
                  );
                })}
              </div>
            </div>
            <div>
              <div className="text-[24px]">数量：</div>
              <div className="mt-[12px] w-[100px] text-[16px]">
                <InputNumber
                  min={1}
                  value={params.num}
                  onChange={(e: any) => setParams({ ...params, num: e })}
                />
              </div>
            </div>
            <div className="flex justify-around">
              <Button
                className="mr-[20px] !h-[60px] w-[240px] !text-[24px]"
                onClick={() => toEditor(goods)}
              >
                二次设计
              </Button>
              <Button
                type="primary"
                className="!h-[60px] w-[240px] !text-[24px]"
                onClick={() => toBuy()}
              >
                加入购物车
              </Button>
            </div>
            <div className="flex flex-col gap-[20px]">
              {coupons.map((item: any, index: number) => {
                return (
                  <div
                    key={index}
                    style={{ border: '1px solid #ff9729' }}
                    className="bordre-1 text-grey flex w-[500px] items-center justify-between rounded-[20px] px-[20px] text-[14px] text-[#ff9729]"
                  >
                    <div>
                      {item.name} {item.des}
                    </div>
                    <Button type="primary" onClick={() => receive(item)}>
                      领取
                    </Button>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
      {/* 底部属性 */}
      <div className="mb-[120px] mt-[100px]">
        <Tabs onChange={onTabsChange}>
          <Tabs.TabPane tab="描述" key="desc">
            <div dangerouslySetInnerHTML={{ __html: detail }} />
          </Tabs.TabPane>
          {list.map((item: any) => (
            <Tabs.TabPane tab={item.title} key={item.id}>
              <div dangerouslySetInnerHTML={{ __html: info }} />
            </Tabs.TabPane>
          ))}
        </Tabs>
      </div>
    </div>
  );
}
